package com.example.zhihuhelpapp.api;

import com.google.gson.Gson;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitManager {
    private static RetrofitManager retrofitManager;
    private static final String BASE_URL = "https://www.zhihu.com/api/v4/";//根地址
    private IApiService apiService;

    /**
     * 单例模式
     *
     */
    public static RetrofitManager getInstance() {
        if (retrofitManager == null) {
            synchronized (RetrofitManager.class) {
                if (retrofitManager == null) {
                    retrofitManager = new RetrofitManager();
                }
            }
        }
        return retrofitManager;
    }

    //构造函数
    private RetrofitManager() {
        initRetrofitManager();
    }

    //创建Retrofit实例
    private void initRetrofitManager() {
        // 添加Gson转换器
        //RxJava适配器
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(new Gson())) // 添加Gson转换器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//RxJava适配器
                .client(getHttpClient())
                .build();
        apiService = retrofit.create(IApiService.class);
    }


    public IApiService apiService() {
        return apiService;
    }

    private static OkHttpClient getHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(180, TimeUnit.SECONDS)
                .addInterceptor(new ResponseInterceptor())
                .build();
    }
}
